package com.tuziki.zk.studio.view;

import com.alibaba.fastjson.JSON;
import com.tuziki.zk.studio.service.ZKDataService;
import com.tuziki.zk.studio.util.Constants;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Sannychan on 2015/3/23.
 */
public class ConnectView extends javax.swing.JFrame {

    static Logger logger = Logger.getLogger(ConnectView.class.getName());


    /**
     * Creates new form connectJFrame
     */
    public ConnectView() {
        initComponents();
    }

    private void initComponents() {
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("新建连接");
        setAlwaysOnTop(true);
        setFocusable(true);
        setFocusableWindowState(true);
        newConntectText = new javax.swing.JTextField();
        connect = new javax.swing.JButton("连接");
        connect.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                connectZookeeper();
            }
        });
        cancel = new javax.swing.JButton("取消");
        cancel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                closeConnectWindow();
            }
        });
        jScrollPane1 = new javax.swing.JScrollPane();
        connectHistoryList = new javax.swing.JList();
        connectHistoryList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                connectHistoryListMouseClicked(evt);
            }
        });
        newConnectLabel = new javax.swing.JLabel("zookeeper地址");
        connectHistoryLabel = new javax.swing.JLabel("连接历史");
        connectHistoryList.setModel(new javax.swing.AbstractListModel() {
            List<String> strings = initConnectHistory();

            public int getSize() {
                return strings.size();
            }

            public Object getElementAt(int i) {
                return strings.get(i);
            }
        });
        jScrollPane1.setViewportView(connectHistoryList);
        setContentPane(new JPanel());
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                                .addGap(109, 109, 109)
                                                .addComponent(connect)
                                                .addGap(59, 59, 59)
                                                .addComponent(cancel))
                                        .addGroup(layout.createSequentialGroup()
                                                .addGap(23, 23, 23)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addGroup(layout.createSequentialGroup()
                                                                .addComponent(newConnectLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                                .addComponent(newConntectText, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE))
                                                        .addComponent(connectHistoryLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                .addContainerGap(23, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(35, 35, 35)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(newConntectText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(newConnectLabel))
                                .addGap(18, 18, 18)
                                .addComponent(connectHistoryLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(cancel)
                                        .addComponent(connect))
                                .addGap(30, 30, 30))
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ConnectView().setVisible(true);
            }
        });
    }

    private void closeConnectWindow() {
        this.dispose();
    }

    private void connectHistoryListMouseClicked(java.awt.event.MouseEvent evt) {
        int selectedIndex = connectHistoryList.locationToIndex(evt.getPoint());
        String selectStr = datas.get(selectedIndex);
        newConntectText.setText(selectStr);
    }


    private List<String> initConnectHistory() {

        File historyFile = getHistoryFile();
        if (historyFile.exists()) {
            String content = "";
            try {
                content = FileUtils.readFileToString(historyFile);
            } catch (IOException e) {
                logger.error("zk连接历史读取失败", e);
                datas = new ArrayList<String>();
            }
            datas = JSON.parseArray(content, String.class);
        } else {
            datas = new ArrayList<String>();
        }
        return datas;
    }

    private void saveConnectHistory(String zkAddr) {
        for (String data : datas) {
            if (data.equalsIgnoreCase(zkAddr)) {
                return;
            }
        }
        datas.add(zkAddr);
        String content = JSON.toJSONString(datas);
        File historyFile = getHistoryFile();
        try {
            FileUtils.writeStringToFile(historyFile, content);
        } catch (IOException e) {
            logger.info("保存连接历史文件失败", e);
        }
        logger.info("保存连接历史文件成功");
    }


    private void connectZookeeper() {
        String zkAddr = newConntectText.getText();
        if (zkAddr == null || zkAddr.trim().isEmpty()) {
            JOptionPane.showMessageDialog(
                    this,
                    "非法的zookeeper地址", "警告",
                    JOptionPane.WARNING_MESSAGE
            );
            return;
        }
        this.dispose();
        saveConnectHistory(zkAddr);
        ZKDataService.initTreeData(zkAddr);
    }


    private static File getHistoryFile() {
        String userHome = System.getProperty("user.home");
        File historyFile = new File(userHome + File.separator + Constants.CONNECT_HOISTORY_FILE);
        logger.info("连接历史文件：" + historyFile.toString());
        return historyFile;
    }

    private javax.swing.JButton cancel;
    private javax.swing.JButton connect;
    private javax.swing.JLabel connectHistoryLabel;
    private javax.swing.JList connectHistoryList;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel newConnectLabel;
    private javax.swing.JTextField newConntectText;
    private List<String> datas = new ArrayList<String>();
}
